<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

require_once(APPPATH . 'libraries/TwitterAPIExchange.php');

class Home extends SiteController {

    private $twitter;

    public function __construct() {
        parent::__construct();
        $settings = array(
            'oauth_access_token' => "2440641433-locaRY7KHC9h2S0fvBOs78F9eo3g8ct8b36Jzj6",
            'oauth_access_token_secret' => "Zo1etRV9NWE0puZ598noY5RpkzgpzJVEVdxxTFBoiOEO4",
            'consumer_key' => "TpEHcmXe8QnhgKdsuXF40oUQ3",
            'consumer_secret' => "Z7YSeYfLJYxIaaYJUjUJFyVz2zpN5mXIqf07lEtruJU68IgfYX"
        );
        $this->twitter = new TwitterAPIExchange($settings);
    }

    public function index() {
        $tela_inicial = $this->doctrine->em->getRepository('TelasIniciais')->findAll();
        if ($tela_inicial != null && count($tela_inicial) > 0) {
            $this->assign('texto', $tela_inicial[0]->get_texto());
            $this->assign('titulo', $tela_inicial[0]->get_titulo());
        }
        $this->assign('tweets', $this->get_tweets());
        $this->assign('user', $this->get_user());
        $this->display('home/index');
    }

    /////////////////////////////////////

    private function get_tweets() {
        try {

            $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
            $getfield = '?screen_name=ramosppedro';
            $requestMethod = 'GET';
            return json_decode($this->twitter
                            ->setGetfield($getfield)
                            ->setGetfield('?count=20')
                            ->buildOauth($url, $requestMethod)
                            ->performRequest());
        } catch (Exception $ex) {
            echo "Erro na comunicação com Twitter API 1.1";
            return null;
        }
    }

    private function get_user() {
        try {

            $url = 'https://api.twitter.com/1.1/users/show.json';
            $getfield = '?screen_name=ramosppedro';
            $requestMethod = 'GET';
            $json = $this->twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest();
            return json_decode($json);
        } catch (Exception $ex) {
            echo "Erro na comunicação com Twitter API 1.1";
            return null;
        }
    }

}
